import { getMapAssetURL } from './loadAssets'
import { useUnitInfo, useBlkcd } from '@/store/modules/compute-methods.js'
import {
  useDispatchManageBlkcd,
  useDispatchManage,
  useDispatchManage1,
  useDispatchManageBlkcdGc
} from '@/store/modules/dispatch-manage.js'
import { storeToRefs } from 'pinia'
import emitter from '@/utils/bus'

/**
 * 创建图层
 * @param {Object} map 地图实例
 * @param {String} layerId 图层编号
 */
export function createLayer(map, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  if (graphicLayer) {
    graphicLayer.clear()
  } else {
    graphicLayer = new mars2d.layer.GraphicLayer({ id: layerId })

    map.addLayer(graphicLayer)
  }

  return graphicLayer
}

/**
 * 清空图层
 * @param {Object} map 地图实例
 * @param {String} layerId 图层编号
 */
export function clearLayer(map, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer && graphicLayer.clear()
}
/**
 * 移除图层
 * @param {Object} map 地图实例
 * @param {String} layerId 图层编号
 */
export function removeLayer(map, layerId) {
  let layer = map.getLayerById(layerId)
  layer && map.removeLayer(layer)
}

/**
 * 清空Geo图层组
 * @param {Object} map 地图实例
 * @param {String} layerId 图层编号
 */
export function clearGeoLayer(map, layerId) {
  let geoLayer = map.getLayerById(layerId)
  geoLayer && geoLayer.clearLayers()
}
/**
 * 清空图层
 * @param {Object} map 地图实例
 * @param {Array} layerIds 图层编号数组
 */
export function clearLayers(map, layerIds = []) {
  layerIds.forEach((layerId) => {
    let graphicLayer = map.getLayerById(layerId)
    graphicLayer && graphicLayer.clear()
  })
}

/**
 * 地图定位
 * @param {Object} map 地圖实例
 * @param {Number} longitude 经度
 * @param {Number} lantitude 纬度
 * @param {Number} zoom 级别
 */
export function locatePoint(map, longitude, lantitude, zoom) {
  if (map != null) {
    map.flyTo([lantitude, longitude], zoom, { duration: 0 })
  }
}

/**
 * 溃坝相关水库-颜色
 * @param {Object} map 地图实例
 * @param {Array} items
 * @param {String} layerId 图层编号
 * @param {Function} clickCallBack 点击回调事件
 */
export function addSecColorPoints(mapInstance, items = [], layerId, clickCallBack = null) {
  let graphicLayer = mapInstance.getLayerById(layerId)
  if (graphicLayer) {
    graphicLayer.clear()
  } else {
    // 无数据时不做处理,直接返回，不再创建图层
    if (!items.length) return
    graphicLayer = new mars2d.layer.GraphicLayer({ id: layerId, pane: 'markerPane' })
    // graphicLayer.on('click', function (event) {
    //   const attr = event.layer.attr
    //   clickCallBack && clickCallBack(attr)
    // })
    mapInstance.addLayer(graphicLayer)
  }

  items.forEach((item) => {
    const { lon, lat, blkcd } = item
    // 无坐标点位时，不做渲染
    console.log(lon, lat, blkcd)

    if (!lon || !lat) return

    // if (value == 0) return

    const graphic = new mars2d.graphic.Point({
      id: blkcd,
      latlng: [lat, lon],
      style: {
        pixelSize: 6,
        color: '#409eff',
        radius: 6, // 半径
        outline: true // 是否有边框
      },
      attr: item
    })
    const label = new mars2d.graphic.Label({
      latlng: [lat, lon], // 与点的位置相同

      style: {
        text: item.blknm, // 标签文本
        font_size: 14, // 字体样式
        color: '#0000FF',
        offsetY: 15
      }
    })

    // 绑定元素提示信息
    // graphic.bindTooltip(getMapTooltipHtml(layerId, item), { direction: 'top' })
    // 将元素添加到图层中
    graphicLayer.addGraphic(graphic)
    graphicLayer.addGraphic(label)
  })
}
/**
 * 查询元素
 * @param {Object} map 地图实例
 * @param {String} layerId 图层编号
 * @param {String} id 要素编号
 */
export function queryGraphicById(map, layerId, id) {
  let graphicLayer = map.getLayerById(layerId)
  if (!graphicLayer) return null

  return graphicLayer.getGraphicById(id)
}

/**
 *
 * @param {Object} map 地图实例
 * @param {String } layerId 图层编号
 */
export function layerIsHaveGraphic(map, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  if (!graphicLayer) return false

  const graphics = graphicLayer.graphics
  return !!graphics.length
}
/**
 * 监测点信息
 * @param {Object} map 地图实例
 * @param {Array} items
 * @param {String} layerId 图层编号
 */
export function addSecPoints(map, items = [], layerId, clickCallBack) {
  let graphicLayer = map.getLayerById(layerId)
  if (graphicLayer) {
    graphicLayer.clear()
  } else {
    graphicLayer = new mars2d.layer.GraphicLayer({ id: layerId })

    map.addLayer(graphicLayer)
  }

  // 将查询图层置顶
  graphicLayer.bringToFront()
  //水库
  const iconSw = getMapAssetURL('sw.svg')
  //水文
  const iconSk = getMapAssetURL('sk.svg')
  //zz
  const iconZz = getMapAssetURL('zz.jpg')
  //空
  const iconEmpty = getMapAssetURL('empty.jpg')
  //闸坝
  const iconZb = getMapAssetURL('zb.png')

  // const iconDD = getMapAssetURL('zha.png')
  items.forEach((item) => {
    let icon
    if (item.properties.sttp == 'ZQ') {
      icon = iconSw
    } else if (item.properties.sttp == 'RR') {
      icon = iconSk
    } else if (item.properties.sttp == 'DD' || item.properties.sttp == 'DM') {
      icon = iconZb
    } else {
      icon = iconZb
    }
    item.properties.lon = item.geometry.coordinates[0]
    item.properties.lat = item.geometry.coordinates[1]
    const graphic = new mars2d.graphic.Marker({
      id: item.properties.stcd,
      latlng: [item.properties.lat, item.properties.lon],
      style: {
        image: icon,
        width: 13,
        height: 13,
        horizontalOrigin: mars2d.HorizontalOrigin.CENTER,
        verticalOrigin: mars2d.VerticalOrigin.CENTER
      },
      attr: item.properties
    })

    // graphic.bindTooltip(`${item.properties.NAME}`, { direction: 'right' })

    graphicLayer.addGraphic(graphic)

    graphicLayer.on('click', function (event) {
      const attr = event.layer.attr
      // 使用放大弹框

      // let { blkcdGc } = storeToRefs(useDispatchManageBlkcdGc())
      // blkcdGc.value = JSON.parse(JSON.stringify(event.layer.attr.blkcd))
      // let { blkcd } = storeToRefs(useDispatchManageBlkcd())
      // blkcd.value = JSON.parse(JSON.stringify(event.layer.attr.blkcd))
      storeToRefs(useDispatchManageBlkcd()).blkcd.value = JSON.parse(
        JSON.stringify(event.layer.attr.blkcd)
      )
      storeToRefs(useDispatchManageBlkcdGc()).blkcdGc.value = JSON.parse(
        JSON.stringify(event.layer.attr.blkcd)
      )
      switch (storeToRefs(useDispatchManage1()).leftSelectList.value) {
        case '实测预报降雨':
          storeToRefs(useDispatchManageBlkcd()).showDialogResult.value = true
          break
        case '实测预报降雨':
          storeToRefs(useDispatchManageBlkcd()).showDialogResult.value = true
          break
        case '典型场次':
          storeToRefs(useDispatchManageBlkcd()).showDialogResult.value = true
          break
        case '模拟降雨':
          storeToRefs(useDispatchManageBlkcd()).showDialogResult.value = true
          break
        case '工程调度':
          storeToRefs(useDispatchManageBlkcd()).showDialogResultGc.value = true
          break

        default:
          break
      }
      // if (storeToRefs(useDispatchManage1()).leftSelectList.value) {

      // }
      // storeToRefs(useDispatchManageBlkcd()).showDialogResult.value = true
      // console.log(useDispatchManageBlkcdGc().blkcdGc,useDispatchManageBlkcd().blkcd,'地图传值');
    })

    // popup
    if (storeToRefs(useDispatchManage()).secRes.value.length) {
      graphicLayer.bindTooltip(
        function (event) {
          console.log(event.attr, 777777)
          // if (event.attr.sttp == 'ZQ') {
          let { secRes } = storeToRefs(useDispatchManage())

          let newArr = secRes?.value?.filter((e) => {
            return e.blkcd == event.attr.blkcd
          })
          // 水文站转换
          let waterSwitch = function (val) {
            switch (val) {
              case 0:
                return '河道正常'
              case 1:
                return '河道超警戒'
              case 2:
                return '河道超保证'
              case undefined:
                return '--'
              default:
                '--'
                break
            }
          }
          // 水库转换
          let waterSwitchStore = function (val) {
            console.log(val, '警戒状态')
            switch (val) {
              case 0:
                return '正常'
              case 1:
                return '超汛限'
              case 2:
                return '超允许雍高'
              case 3:
                return '超警戒'
              case 4:
                return '超允许最高'
              case undefined:
                return '--'
              default:
                '--'
                break
            }
          }

          if (newArr[0]?.sttp == 'ZQ') {
            return `<div class="custom-tooltip">
                  <div class="custom-tooltip-title">
                    <span>${event.attr.blknm || '--'} - ${event.attr.blkcd || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">预报洪峰时间：</span>
                    <span class="container-right">${newArr[0]?.fcMxt || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">预报洪峰流量(m³/s)：</span>
                    <span class="container-right">${newArr[0]?.fcMxq || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">预报洪峰水位(m)：</span>
                    <span class="container-right">${newArr[0]?.fcMxz || '--'}</span>
                  </div>

                  <div class="custom-tooltip-container">
                    <span class="container-left">警戒状态：</span>
                    <span class="container-right">${waterSwitch(newArr[0]?.wnstatus)}</span>
                  </div>
                  <div class="custom-tooltip-container custom-warning">
                    <span class="container-left ">超过的值(m)：</span>
                    <span class="container-right">${newArr[0]?.sz || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">警戒水位(m)：</span>
                    <span class="container-right">${newArr[0]?.warnInfo?.wrz || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">保证水位(m)：</span>
                    <span class="container-right">${newArr[0]?.warnInfo?.grz || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">警戒流量(m³/s)：</span>
                    <span class="container-right">${newArr[0]?.warnInfo?.wrq || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">保证流量(m³/s)：</span>
                    <span class="container-right">${newArr[0]?.warnInfo?.grq || '--'}</span>
                  </div>
                </div>`
          } else {
            return `<div class="custom-tooltip">
                  <div class="custom-tooltip-title">
                    <span>${event.attr.blknm || '--'} - ${event.attr.blkcd || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">预报洪峰时间：</span>
                    <span class="container-right">${newArr[0]?.fcMxt || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">预报洪峰流量(m³/s)：</span>
                    <span class="container-right">${newArr[0]?.fcMxq || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">最大出流(m³/s)：</span>
                    <span class="container-right">${newArr[0]?.fcMxotq || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">预报洪峰水位(m)：</span>
                    <span class="container-right">${newArr[0]?.fcMxz || '--'}</span>
                  </div>

                  <div class="custom-tooltip-container">
                    <span class="container-left">预报洪峰时间：</span>
                    <span class="container-right">${newArr[0]?.fcMxt || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">警戒状态：</span>
                    <span class="container-right">${waterSwitchStore(newArr[0]?.wnstatus)}</span>
                  </div>
                  <div class="custom-tooltip-container">
                  <span class="container-left">超过的值(m)：</span>
                    <span class="container-right">${newArr[0]?.sz || '--'}</span>
                  </div>
                <div class="custom-tooltip-container">
                    <span class="container-left">警戒水位(m)：</span>
                    <span class="container-right">${newArr[0]?.warnInfo?.wrz || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">保证水位(m)：</span>
                    <span class="container-right">${newArr[0]?.warnInfo?.grz || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">警戒流量(m³/s)：</span>
                    <span class="container-right">${newArr[0]?.warnInfo?.wrq || '--'}</span>
                  </div>
                  <div class="custom-tooltip-container">
                    <span class="container-left">保证流量(m³/s)：</span>
                    <span class="container-right">${newArr[0]?.warnInfo?.grq || '--'}</span>
                  </div>
                </div>`
          }
        },
        {
          direction: 'top',
          className: 'custom-tooltip'
        }
      )
    } else {
    }
  })
}
/**
 * 添加断面名称
 * @param {*} map 地图实例
 * @param {Array} items
 * @param {*} layerId 图层编号
 */
export function addSecName(map, items = [], layerId) {
  let graphicLayer = map.getLayerById(layerId)
  if (graphicLayer) {
    graphicLayer.clear()
  } else {
    graphicLayer = new mars2d.layer.GraphicLayer({ id: layerId })
    map.addLayer(graphicLayer)
  }
  items.forEach((item) => {
    let style
    if (item.properties.PMT == 2 || item.properties.sttp == 'ZQ') {
      style = createMarkTextStyle(item.properties.blknm, '#FF0033')
    } else if (item.properties.PMT == 1 || item.properties.STTP == 'RR') {
      style = createMarkTextStyle(item.properties.blknm, '#0033FF')
    } else {
      // style = createMarkTextStyle(item.properties.blknm, '#FF0033')
      style = createMarkTextStyle(item.properties.blknm, '#0033FF')
    }
    item.properties.lon = item.geometry.coordinates[0]
    item.properties.lat = item.geometry.coordinates[1]
    const graphic = new mars2d.graphic.Point({
      latlng: [item.properties.lat, item.properties.lon],
      style: style
    })
    graphicLayer.addGraphic(graphic)
  })
}

/**
 * 添加计算单元
 * @param {*} map 地图实例
 * @param {*} geoJson 图层数据
 * @param {*} layerId 图层编号
 */
export function addJsUnit(map, geoJson, layerId) {
  let geoJsonLayer = map.getLayerById(layerId)
  if (geoJsonLayer) {
    //geoJsonLayer.load({ data: geoJson })
    geoJsonLayer.clear()
  } else {
    geoJsonLayer = new mars2d.layer.GraphicLayer({
      id: layerId,
      name: '计算单元',
      data: geoJson,
      symbol: {
        type: 'polygon',
        styleOptions: {
          weight: 1,
          fillOpacity: 0.6,
          fillColor: '#0033CC',
          color: '#000000',
          fill: false
        }
      },
      flyTo: false
    })
  }
  map.addLayer(geoJsonLayer)

  geoJsonLayer.loadGeoJSON(geoJson)
  //geoJsonLayer.bringToBack()
}
/**
 * 添加计算单元-无方案
 * @param {*} map 地图实例
 * @param {*} geoJson 图层数据
 * @param {*} layerId 图层编号
 */
export function addJsUnitNoScheme(map, geoJson, layerId) {
  let geoJsonLayer = map.getLayerById(layerId)
  if (geoJsonLayer) {
    //geoJsonLayer.load({ data: geoJson })
    geoJsonLayer.clear()
  } else {
    geoJsonLayer = new mars2d.layer.GraphicLayer({
      id: layerId,
      name: '计算单元',
      data: geoJson,
      symbol: {
        type: 'polygon',
        styleOptions: {
          weight: 1,
          fillOpacity: 0.8,
          fillColor: '#ffffff',
          color: 'pink',
          fill: false
        }
      },
      flyTo: false
    })
    map.addLayer(geoJsonLayer)
  }
  geoJsonLayer.loadGeoJSON(geoJson)
  //geoJsonLayer.bringToBack()
}
/**
 * 更新计算单元Graphic 样式
 * @param {*} layerId
 */
export function changeJsUnitGraphic(map, dataJson, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer.eachGraphic((graphic) => {
    const attr = graphic.attr
    const blkcd = attr.BLKCD
    const data = dataJson.filter(function (item) {
      return item.blkcd == blkcd
    })
    const calStatus = data[0] && data[0].calStatus

    let style = {}
    //1:等待中 2：计算中 3:已完成 4：异常 0：未启动
    // 0：未启动 1: 等待中 2：水文计算中 3：水库调度中 4: 已完成 5：异常
    if (calStatus == 1) {
      style = createPolygonStyle('#86e7fe')
    } else if (calStatus == 2) {
      style = createPolygonStyle('#00FF7F')
    } else if (calStatus == 3) {
      style = createPolygonStyle('#006994')
    } else if (calStatus == 4) {
      style = createPolygonStyle('#008000')
    } else if (calStatus == 5) {
      style = createPolygonStyle('#FF0000')
    } else {
      style = createPolygonStyle('#999d9c')
    }
    graphic.setStyle(style)
  })
}
/**
 * 选择区域计算单元Graphic
 * @param {*} layerId
 */
export function handleClickJsUnitGraphic(map, selectedData, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer.eachGraphic((graphic) => {
    const attr = graphic.attr
    const blkcd = attr.BLKCD
    // let data = dataJson.filter(function(item) {
    //     return item.blkcd == blkcd
    // })
    let style = {}
    if (selectedData.length > 0) {
      selectedData.forEach((item) => {
        if (item.blkcd == blkcd) {
          style = createPolygonStyle('#ffffff')
        }
      })
    }
    graphic.setStyle(style)
  })
}
/**
 * 选择预报断面计算单元Graphic
 * @param {*} layerId
 */
export function handleClickSecGraphic(map, secId, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer.eachGraphic((graphic) => {
    const attr = graphic.attr
    const blkcd = attr.BLKCD
    // let data = dataJson.filter(function(item) {
    //     return item.blkcd == blkcd
    // })
    let style = {}
    if (blkcd == secId) {
      style = createPolygonStyle('#008000')
    }
    graphic.setStyle(style)
  })
}
/**
 * 更新计算单元Graphic 样式-根据方案
 * @param {*} layerId
 */
export function changeJsUnitSchemeGraphic(map, dataJson, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer.eachGraphic((graphic) => {
    const attr = graphic.attr
    const blkcd = attr.BLKCD
    const data = dataJson.find(function (item) {
      return item.blkcd == blkcd
    })
    const unitModel = data.unitModel
    let style = {}
    //1:时空变源 2： 新安江
    if (unitModel == 1) {
      style = createPolygonStyle('#0033CC')
    } else if (unitModel == 2) {
      style = createPolygonStyle('#66CC33')
    }
    graphic.setStyle(style)
  })
}
/**
 * 更新计算单元Graphic 样式-根据预报断面选择
 * @param {*} layerId
 */
export function changeJsUnitSecGraphic(map, secBlkcd, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  console.log(graphicLayer.getBounds())
  graphicLayer.eachGraphic((graphic) => {
    const attr = graphic.attr
    const blkcd = attr.BLKCD
    let style = {}
    if (blkcd == secBlkcd) {
      style = createPolygonStyle('#999d9c')
      map.flyToBounds(graphic._bounds)
    } else {
      style = { weight: 0.3, fillOpacity: 0.8, fillColor: '#ffffff', color: 'pink', fill: true }
    }
    graphic.setStyle(style)
  })
}
/**
 * 添加拓扑线
 * @param {*} map 地图实例
 * @param {*} geoJson 图层数据
 * @param {*} layerId 图层编号
 */
export function addTopology(map, geoJson, layerId) {
  let topologyLayer = map.getLayerById(layerId)
  if (topologyLayer) {
    topologyLayer.clear()
  } else {
    //topologyLayer = createTopologyGeoJsonLayer(geoJson, layerId)
    topologyLayer = new mars2d.layer.GraphicLayer({ id: layerId })
    map.addLayer(topologyLayer)
  }
  createTopologyDecoratorLayer(topologyLayer, geoJson)
}
/**
 * 创建GeoJSONLayer的拓扑线
 * @param {*} geoJson
 * @returns
 */
export function createTopologyGeoJsonLayer(geoJson, layerId) {
  const geoJsonLayer = new mars2d.layer.GeoJsonLayer({
    id: layerId,
    name: '站点拓扑线',
    data: geoJson,
    symbol: {
      styleOptions: {
        type: 'polyline',
        weight: 1,
        color: '#0000FF'
      }
    },
    flyTo: false
  })
  return geoJsonLayer
}
/**
 * 创建带箭头的拓扑线
 * @param {*} geoJson
 * @returns
 */
export function createTopologyDecoratorLayer(graphicLayer, geoJson) {
  const features = geoJson.features
  features.forEach((item) => {
    const coordinates = item.geometry.coordinates
    const latLngs = mars2d.L.GeoJSON.coordsToLatLngs(
      coordinates,
      0,
      mars2d.L.GeoJSON.coordsToLatLng
    )
    // 代表折线对象
    const pLine = mars2d.L.polyline(latLngs, { weight: 1, color: '#0000FF' })
    const pLineD = mars2d.L.polylineDecorator(pLine, {
      patterns: [
        {
          offset: 30, // 箭头起始位置距离线条两端的距离
          repeat: 100, // 箭头重复的间隔
          symbol: mars2d.L.Symbol.arrowHead({
            pixelSize: 4, // 箭头大小
            headAngle: 75, // 角度
            polygon: false,
            pathOptions: { stroke: true, weight: 1.5, color: '#0000FF' }
          })
        }
      ]
    })
    graphicLayer.addLayer(pLine)
    graphicLayer.addLayer(pLineD)
  })
  return graphicLayer
}
/**
 * 添加小流域图层
 * @param {*} map
 * @param {*} geoJson
 * @param {*} layerId
 */
export function addWataLayer(map, geoJson, layerId) {
  let geoJsonLayer = map.getLayerById(layerId)
  if (geoJsonLayer) {
    geoJsonLayer.clear()
  } else {
    geoJsonLayer = new mars2d.layer.GraphicLayer({
      id: layerId,
      name: '小流域',
      symbol: {
        type: 'polygon',
        styleOptions: {
          weight: 0.3,
          fillOpacity: 0.6,
          fillColor: '#FFFF00',
          color: '#FFFF00',
          fill: false
        }
      },
      flyTo: false
    })
    map.addLayer(geoJsonLayer)
  }
  geoJsonLayer.loadGeoJSON(geoJson)
}
/**
 * 添加河流图层
 * @param {*} map
 * @param {*} geoJson
 * @param {*} layerId
 */
export function addRiverLayer(map, geoJson, layerId) {
  let geoJsonLayer = map.getLayerById(layerId)
  if (geoJsonLayer) {
    geoJsonLayer.clear()
  } else {
    geoJsonLayer = new mars2d.layer.GraphicLayer({
      id: layerId,
      name: '河流',
      data: geoJson,
      symbol: {
        type: 'polyline',
        styleOptions: {
          weight: 1,
          color: '#0000FF'
        }
      },
      flyTo: false
    })
    map.addLayer(geoJsonLayer)
  }
  geoJsonLayer.loadGeoJSON(geoJson)
}
/**
 * 添加节点图层
 * @param {*} map
 * @param {*} geoJson
 * @param {*} layerId
 */
export function addNodeLayer(map, geoJson, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  if (graphicLayer) {
    graphicLayer.clear()
  } else {
    graphicLayer = new mars2d.layer.GraphicLayer({ id: layerId })
    map.addLayer(graphicLayer)
  }
  const iconEmpty = getMapAssetURL('node.png')
  geoJson.features.forEach((item) => {
    const graphic = new mars2d.graphic.Marker({
      id: item.properties.NDCD,
      latlng: [item.geometry.coordinates[1].toFixed(4), item.geometry.coordinates[0].toFixed(4)],

      style: {
        image: iconEmpty,
        // color: '#00E5EE',
        // color: 'red',
        width: 5,
        height: 5,
        horizontalOrigin: mars2d.HorizontalOrigin.CENTER,
        verticalOrigin: mars2d.VerticalOrigin.CENTER
      },
      attr: item.properties
    })
    // graphic.bindTooltip(`${item.properties.NAME}`, { direction: 'right' })
    graphicLayer.addGraphic(graphic)
    graphicLayer.on('click', function (event) {
      console.log(event, '点击地图')
      let { unitShow } = storeToRefs(useUnitInfo())
      let { blkcd, blknm } = storeToRefs(useBlkcd())
      unitShow.value = true
      blkcd.value = event.layer.attr.NDCD
      blknm.value = 'NDCD'
    })
  })
  // geoJsonLayer.loadGeoJSON(geoJson)
  // 在layer上绑定Popup单击弹窗
}
/////////////////////
/**
 * 创建标注文本图标样式
 * @param {*} ftCon 标注内容
 * @param {*} ftClr 标注字体颜色
 */
export function createMarkDivIcon(ftCon, ftClr) {
  const hm = `<div><i class="icon icon_marker" style="text-align: center; line-height: 22px; color: ${ftClr}; font-style: normal; font-size: 10px; font-weight: bold; text-shadow: #fff 2px 1px 2px">${ftCon}</i></div>`
  const icon = mars2d.L.divIcon({
    iconSize: [85, 26],
    iconAnchor: [16, 26],
    html: hm
  })
  return icon
}
/**
 *  创建标注文本样式
 * @param {*} ftCon 文本内容
 * @param {*} ftClr 文本颜色
 * @returns
 */
export function createMarkTextStyle(ftCon, ftClr) {
  const style = {
    pixelSize: 0,
    color: ftClr,
    text: ftCon,
    textStyle: {
      stroke: true,
      color: ftClr,
      font: "11px 'Microsoft Yahei'",
      offsetX: 10,
      offsetY: 5
    },
    zIndex: 0
  }

  return style
}
/**
 * 创建面样式
 * @param {*} ftClr
 * @returns
 */
export function createPolygonStyle(ftClr) {
  const style = {
    weight: 1,
    fillOpacity: 0.8,
    fillColor: ftClr,
    color: '#000000',
    fill: true
  }
  return style
}

////////动态图层操作
/**
 * 添加动态图层数据
 * @param {*} map 地图实例
 * @param {*} layerPath 图层地址
 * @param {*} layerId 图层编号
 */
export function addDynamicLayer(map, layerPath, layerIndexs, layerId) {
  let layer = map.getLayerById(layerId)
  if (layer) {
    map.removeLayer(layer)
  } else {
    layer = new mars2d.layer.ArcGisDynamicLayer({
      name: layerId,
      id: layerId,
      url: layerPath,
      layers: layerIndexs,
      opacity: 1,
      zIndex: 0
    })
    map.addLayer(layer)
  }
}
////////动态/切片图层操作
/**
 * 添加切片图层数据-全部显示
 * @param {*} map 地图实例
 * @param {*} layerPath 图层地址
 * @param {*} layerId 图层编号
 */
export function addTileLayer(map, layerPath, layerIndex, layerId, name) {
  let layer = map.getLayerById(layerId)
  if (layer) {
    map.removeLayer(layer)
  } else {
    layer = new mars2d.layer.ArcGisTileLayer({
      name: name,
      id: layerId,
      url: layerPath,
      zIndex: layerIndex
    })
    map.addLayer(layer)
  }
}
////////动态图层操作
/**
 * 添加动态图层数据-全部显示
 * @param {*} map 地图实例
 * @param {*} layerPath 图层地址
 * @param {*} layerId 图层编号
 */
export function addDynamicLayerShowAll(map, layerPath, layerIndex, layerId, name, layers) {
  let layer = map.getLayerById(layerId)
  if (layer) {
    map.removeLayer(layer)
  }
  layer = new mars2d.layer.ArcGisDynamicLayer({
    name: name,
    id: layerId,
    url: layerPath,
    opacity: 1,
    f: 'image',
    zIndex: layerIndex,
    layers: [layers]
  })
  map.addLayer(layer)
}

/**
 * 点击计算单元，修改断面样式
 * @param {*} map 地图实例
 * @param {*} layerPath 图层地址
 * @param {*} layerId 图层编号
 */
export function clickMapSection(map, dataJson, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer.off('click')
  graphicLayer.on('click', function (event) {
    let isSecTion = dataJson.filter((item) => {
      return item.blkcd == event.layer.attr.BLKCD
    })
    if (isSecTion.length > 0) {
      event.layer.setStyle(createPolygonStyle('#008000'))
      let { unitShow } = storeToRefs(useUnitInfo())
      let { blkcd, status, blknm } = storeToRefs(useBlkcd())
      unitShow.value = true
      blkcd.value = event.layer.attr.BLKCD
      blknm.value = event.layer.attr.BLKNM
      status.value = isSecTion[0].status
    } else {
      //
    }
  })
}
/**
 * 点击断面,更新计算单元配置状态
 * @param {*} map 地图实例
 * @param {*} layerPath 图层地址
 * @param {*} layerId 图层编号
 */
export function updateJsUnitGraphic(map, dataJson, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer.eachGraphic((graphic) => {
    const attr = graphic.attr
    const blkcd = attr.BLKCD
    const data = dataJson.filter(function (item) {
      return item.blkcd == blkcd
    })
    const status = data[0] && data[0].status
    let style = {}
    //0 未配置 1已配置
    if (status == 0) {
      style = createPolygonStyle('#ffffff')
    } else if (status == 1) {
      style = createPolygonStyle('#00FF7F')
    } else {
      style = createPolygonStyle('#999d9c')
    }
    graphic.setStyle(style)
  })
}
/**
 * 定位到某个计算单元
 * @param {*} layerId
 */
export function updateJsUnitSecGraphic(map, secBlkcd, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer.eachGraphic((graphic) => {
    const attr = graphic.attr
    const blkcd = attr.BLKCD
    if (blkcd == secBlkcd) {
      map.flyToBounds(graphic._bounds)
    }
  })
}
/**
 * 定位到某个小流域
 * @param {*} layerId
 */
export function positionRiver(map, riverCd, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  graphicLayer.eachGraphic((graphic) => {
    console.log('666', graphic)
    const attr = graphic.attr
    const ricd = attr.WSCD
    if (ricd == riverCd) {
      map.flyToBounds(graphic._bounds)
    }
  })
}

/**
 * 添加流域矢量切片图层(小流域\河道)
 * @param {*} map
 * @param {*} layerUrl 地图url
 * @param {*} id 图层id
 */
export function addBasinVectorTiles(map, layerUrl, id, styles) {
  var arr = new L.vectorGrid.protobuf(layerUrl, {
    id: id,
    rendererFactory: L.canvas.tile,
    vectorTileLayerStyles: styles,
    interactive: true, // 启用交互
    pane: 'tilePane'
  }).addTo(map)
  arr.bringToFront()
  console.log('777', arr)
  arr.off('click')
  arr.on('click', function (event) {
    let { unitShow } = storeToRefs(useUnitInfo())
    let { blkcd, status, blknm } = storeToRefs(useBlkcd())
    unitShow.value = true

    if (event.layer.properties.rvcd) {
      blkcd.value = event.layer.properties.rvcd
      blknm.value = 'rvcd'
    } else {
      blkcd.value = event.layer.properties.wscd
      blknm.value = 'wscd'
    }
  })
}
export function clickFlowMap(map, id) {
  let graphicLayer = map.getLayerById(id)
}
/**
 * 删除数量切片图层
 * @param {*} map
 * @param {*} id
 */
export function removeBasinVectorTiles(map, id) {
  for (let i in map._layers) {
    if (map._layers[i].options && map._layers[i].options.id && map._layers[i].options.id == id) {
      map.removeLayer(map._layers[i])
      break
    }
  }
}
//添加雨量站
export function addRainLayer(map, geoJson, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  if (graphicLayer) {
    graphicLayer.clear()
  } else {
    graphicLayer = new mars2d.layer.GraphicLayer({ id: layerId })
    map.addLayer(graphicLayer)
  }
  const iconSw = getMapAssetURL('zz.png')
  geoJson.features.forEach((item) => {
    const graphic = new mars2d.graphic.Marker({
      id: item.properties.NDCD,
      latlng: [item.geometry.coordinates[1].toFixed(4), item.geometry.coordinates[0].toFixed(4)],

      style: {
        image: iconSw,
        // color: '#00E5EE',
        // color: 'red',
        width: 8,
        height: 8,
        horizontalOrigin: mars2d.HorizontalOrigin.CENTER,
        verticalOrigin: mars2d.VerticalOrigin.CENTER
      },
      attr: item.properties
    })
    // graphic.bindTooltip(`${item.properties.NAME}`, { direction: 'right' })
    graphicLayer.addGraphic(graphic)
    graphicLayer.on('click', function (event) {
      console.log(event, '点击地图')
      let { unitShow } = storeToRefs(useUnitInfo())
      let { blkcd, blknm } = storeToRefs(useBlkcd())
      unitShow.value = true
      blkcd.value = event.layer.attr.NDCD
      blknm.value = 'NDCD'
    })
  })
  // geoJsonLayer.loadGeoJSON(geoJson)
}

/**
 * 把multipolygon转换成leaflet加载的坐标串
 * @param {*} multipolygon
 * @returns
 */
export function multipolygonToLnglats(multipolygon) {
  const polygons = multipolygon
    .substring(multipolygon.indexOf('((') + 2, multipolygon.lastIndexOf('))'))
    .split('),(')
  const latlngs = []
  polygons.forEach((polygon) => {
    const coords = polygon.split(',')
    const latlng = []
    coords.forEach((coord) => {
      const latlngStr = coord.trim().replace('(', '').replace(')', '').split(' ')
      latlng.push([parseFloat(latlngStr[1]), parseFloat(latlngStr[0])])
    })
    latlngs.push(latlng)
  })
  return latlngs
}

/**
 * 添加一个面到地图上 并定位到要素位置
 * @param {*} map
 * @param {*} latlngs  坐标
 * @param {*} layerId  图层编号
 */
export function addTopologyPosition(map, latlngs, layerId, styles) {
  let locationLayer = map.getLayerById(layerId)
  if (locationLayer) {
    locationLayer.clear()
  } else {
    locationLayer = new mars2d.layer.GraphicLayer({ id: layerId })
    map.addLayer(locationLayer)
  }
  const graphic = new mars2d.graphic.Polygon({
    latlngs: latlngs,
    style: styles
  })
  locationLayer.addGraphic(graphic)
  locationLayer.flyTo({ duration: 2 })
}
export function addTopologyOne(map, latlngs, layerId) {
  let locationLayer = map.getLayerById(layerId)
  if (locationLayer) {
    locationLayer.clear()
  } else {
    locationLayer = new mars2d.layer.GraphicLayer({ id: layerId })
    map.addLayer(locationLayer)
  }
  const graphic = new mars2d.graphic.Polygon({
    latlngs: latlngs,
    style: {
      fill: true,
      fillColor: '#1a8e17',
      fillOpacity: 0.6,
      outline: true,
      outlineWidth: 1,
      outlineColor: '#0000FF',
      outlineOpacity: 0.5
    }
  })
  locationLayer.addGraphic(graphic)
  locationLayer.flyTo({ duration: 2 })
}
//添加JSON 并定位
export function addGeojsontoFly(map, geoJson, layerId, styles) {
  let geoJsonLayer = map.getLayerById(layerId)
  if (geoJsonLayer) {
    //geoJsonLayer.load({ data: geoJson })
    geoJsonLayer.clear()
  } else {
    geoJsonLayer = new mars2d.layer.GraphicLayer({
      id: layerId,
      name: 'geoJson',
      data: geoJson,
      symbol: {
        type: 'polygon',
        styleOptions: styles
      },
      flyTo: true
    })
  }
  map.addLayer(geoJsonLayer)
  geoJsonLayer.loadGeoJSON(geoJson)
  // map.flyToBounds(geoJsonLayer.getBounds())
  geoJsonLayer.flyTo({ duration: 2 })
}
// 用线表示区域 并定位
export function addGeojsontoFlyLine(map, geoJson, layerId, styles) {
  let geoJsonLayer = map.getLayerById(layerId)
  if (geoJsonLayer) {
    //geoJsonLayer.load({ data: geoJson })
    geoJsonLayer.clear()
  } else {
    geoJsonLayer = new mars2d.layer.GraphicLayer({
      id: layerId,
      name: 'geoJson',
      data: geoJson,
      symbol: {
        type: 'polyline',
        styleOptions: styles
      },
      flyTo: true
    })
  }
  map.addLayer(geoJsonLayer)
  geoJsonLayer.loadGeoJSON(geoJson)
  // map.flyToBounds(geoJsonLayer.getBounds())
  geoJsonLayer.flyTo({ duration: 2 })
}
/**
 * 在地图上添加一张照片
 * @param {*} map
 * @param {*} layerId
 * @param {*} url
 * @param {*} xmin
 * @param {*} ymin
 * @param {*} xmax
 * @param {*} ymax
 */
export function addImageToMap(map, layerId, url, xmin, ymin, xmax, ymax, scid) {
  let locationLayer = map.getLayerById(layerId)
  if (locationLayer) {
    map.removeLayer(locationLayer)
  }
  let _url = `${url}?xmin=${xmin}&ymin=${ymin}&xmax=${xmax}&ymax=${ymax}&scid=${scid}&tm=${new Date().getTime()}`
  console.log(_url)
  const tileLayer = new mars2d.layer.ImageLayer({
    id: layerId,
    url: _url,
    rectangle: { xmin: xmin, xmax: xmax, ymin: ymin, ymax: ymax },
    // crs: mars2d.CRS.EPSG3857,
    zIndex: 1000
  })
  map.addLayer(tileLayer)
}

//添加预报对象总雨量 流量 切片
export function addRainFlowtoMap(map, url, layerId, type) {
  ;(properties) => {
    console.log(properties, '123')
    var color
    if (type == 1) {
      //fcmxqtype 雨量1到7   pavtype洪峰流量1-6
      if (properties.fcmxqtype == 1) {
        color = 'rgb(174, 174, 174)'
      } else if (properties.fcmxqtype == 2) {
        color = 'rgb(167, 240, 143)'
      } else if (properties.fcmxqtype == 3) {
        color = 'rgb(62, 184, 62)'
      } else if (properties.fcmxqtype == 4) {
        color = 'rgb(98, 183, 255)'
      } else if (properties.fcmxqtype == 5) {
        color = 'rgb(0, 0, 253)'
      } else if (properties.fcmxqtype == 6) {
        color = 'rgb(249, 1, 249)'
      } else if (properties.fcmxqtype == 7) {
        color = 'rgb(127, 1, 64)'
      }
      return {
        weight: 1,
        fillOpacity: 0.6,
        fillColor: color,
        color: 'black',
        fill: true
      }
    } else if (type == 2) {
      if (properties.pavtype == 1) {
        color = 'rgb(174, 174, 174)'
      } else if (properties.pavtype == 2) {
        color = 'rgb(167, 240, 143)'
      } else if (properties.pavtype == 3) {
        color = 'rgb(62, 184, 62)'
      } else if (properties.pavtype == 4) {
        color = 'rgb(98, 183, 255)'
      } else if (properties.pavtype == 5) {
        color = 'rgb(0, 0, 253)'
      } else if (properties.pavtype == 6) {
        color = 'rgb(249, 1, 249)'
      }
      return {
        weight: 1,
        fillOpacity: 0.6,
        fillColor: color,
        color: 'black',
        fill: true
      }
    } else if (type == 3) {
      if (properties.maxflowtype == 1) {
        color = 'rgb(174, 174, 174)'
      } else if (properties.maxflowtype == 2) {
        color = 'rgb(167, 240, 143)'
      } else if (properties.maxflowtype == 3) {
        color = 'rgb(62, 184, 62)'
      } else if (properties.maxflowtype == 4) {
        color = 'rgb(98, 183, 255)'
      } else if (properties.maxflowtype == 5) {
        color = 'rgb(0, 0, 253)'
      } else if (properties.maxflowtype == 6) {
        color = 'rgb(249, 1, 249)'
      }
      return {
        weight: 1,
        color: color
      }
    }
  }
}

//添加计算方案预报对象总雨量 流量 切片
export function addCRainFlowtoMap(map, url, layerId, type, name) {
  ;(properties) => {
    console.log(properties)
    var color
    if (type == 1) {
      //fcmxqtype 雨量1到7   pavtype洪峰流量1-6
      if (properties.fcmxqtype == 1) {
        color = 'rgb(174, 174, 174)'
      } else if (properties.fcmxqtype == 2) {
        color = 'rgb(167, 240, 143)'
      } else if (properties.fcmxqtype == 3) {
        color = 'rgb(62, 184, 62)'
      } else if (properties.fcmxqtype == 4) {
        color = 'rgb(98, 183, 255)'
      } else if (properties.fcmxqtype == 5) {
        color = 'rgb(0, 0, 253)'
      } else if (properties.fcmxqtype == 6) {
        color = 'rgb(249, 1, 249)'
      } else if (properties.fcmxqtype == 7) {
        color = 'rgb(127, 1, 64)'
      }
      return {
        weight: 1,
        fillOpacity: 0.6,
        fillColor: color,
        color: 'black',
        fill: true
      }
    } else if (type == 2) {
      if (properties.pavtype == 1) {
        color = 'rgb(174, 174, 174)'
      } else if (properties.pavtype == 2) {
        color = 'rgb(167, 240, 143)'
      } else if (properties.pavtype == 3) {
        color = 'rgb(62, 184, 62)'
      } else if (properties.pavtype == 4) {
        color = 'rgb(98, 183, 255)'
      } else if (properties.pavtype == 5) {
        color = 'rgb(0, 0, 253)'
      } else if (properties.pavtype == 6) {
        color = 'rgb(249, 1, 249)'
      }
      return {
        weight: 1,
        fillOpacity: 0.6,
        fillColor: color,
        color: 'black',
        fill: true
      }
    } else if (type == 3) {
      if (properties.maxflowtype == 1) {
        color = 'rgb(174, 174, 174)'
      } else if (properties.maxflowtype == 2) {
        color = 'rgb(167, 240, 143)'
      } else if (properties.maxflowtype == 3) {
        color = 'rgb(62, 184, 62)'
      } else if (properties.maxflowtype == 4) {
        color = 'rgb(98, 183, 255)'
      } else if (properties.maxflowtype == 5) {
        color = 'rgb(0, 0, 253)'
      } else if (properties.maxflowtype == 6) {
        color = 'rgb(249, 1, 249)'
      }
      return {
        weight: 1,
        color: color
      }
    }
  }
}
//添加重点站点
export function divGraphicYellow(map, data, layerId) {
  let graphicLayer = map.getLayerById(layerId)
  if (graphicLayer) {
    graphicLayer.clear()
  } else {
    graphicLayer = new mars2d.layer.GraphicLayer({ id: layerId })
    map.addLayer(graphicLayer)
  }
  for (let i = 0; i < data.length; i++) {
    const item = data[i]

    const divGraphic = new mars2d.graphic.DivGraphic({
      latlng: [item.lat, item.lon],
      direction: 'top',
      style: {
        html: `<div class="marsImgPanel2">
              <div class="title"> ${item.blknm}</div>
              <div class="content">
                <div class="water-box">
                  水位:${item.fcMxz}
                 </div>
                <div class="flow-box">
                  流量:${item.fcMxq}
                </div>
              </div>
            </div >`,
        offsetY: 40

        // `<div class="marsTiltPanel marsTiltPanel-theme-red">
        //         <div class="marsTiltPanel-wrap">
        //             <div class="area">
        //                 <div class="arrow-lt"></div>
        //                 <div class="b-t"></div>
        //                 <div class="b-r"></div>
        //                 <div class="b-b"></div>
        //                 <div class="b-l"></div>
        //                 <div class="arrow-rb"></div>
        //                 <div class="label-wrap">
        //                     <div class="title">${item.blknm}</div>
        //                     <div class="label-content">
        //                         <div class="data-li">
        //                             <div class="data-label">流量：</div>
        //                             <div class="data-value"><span id="lablLiuliang" class="label-num">${item.fcMxq}</span><span class="label-unit">m³/s</span>
        //                             </div>
        //                         </div>
        //                         <div class="data-li">
        //                             <div class="data-label">水位：</div>
        //                             <div class="data-value"><span id="lablYeWei"  class="label-num">${item.fcMxz}</span><span class="label-unit">m</span>
        //                             </div>
        //                         </div>

        //                     </div>
        //                 </div>
        //             </div>
        //             <div class="b-t-l"></div>
        //             <div class="b-b-r"></div>
        //         </div>
        //         <div class="arrow" ></div>
        //     </div>`
      },
      attr: {
        index: i + 1,
        duNum: 0
      }
    })
    graphicLayer.addGraphic(divGraphic)
  }
}
